//
//  Utility.m
//  ZTML
//
//  Created by 周涛 on 14/11/6.
//  Copyright (c) 2014年 long. All rights reserved.
//

#import "Utility.h"


@implementation Utility

+ (UIViewController *)currentViewController
{
    UITabBarController *tabbarController = (UITabBarController *)[[UIApplication sharedApplication] keyWindow].rootViewController;
    return [[tabbarController selectedViewController] topViewController];
}

+ (void)showAlertMessage:(NSString *)atMessage
{
    [self showAlertTitle:nil Message:atMessage];
}
/**
 *  弹出消息提示框
 *
 *  @param atTitle   标题
 *  @param atMessage 消息
 */
+ (void)showAlertTitle:(NSString *)atTitle Message:(NSString *)atMessage
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:atTitle message:atMessage preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel                                                                 handler:^(UIAlertAction * action) {
    }];
    [alertController addAction:confirmAction];
    [[self currentViewController] presentViewController:alertController animated:YES completion:nil];
}

/**
 *  同步判断网络连接
 *
 *  @return YES 表示有网络连接
 */
+ (BOOL)networkDetection
{
    NSURL *url1 = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
    return (response != nil);
}

/**
 *  获取主窗口
 *
 *  @return <#return value description#>
 */
+ (UIWindow *)mainWindow
{
    UIApplication *app = [UIApplication sharedApplication];
    if ([app.delegate respondsToSelector:@selector(window)])
    {
        return [app.delegate window];
    }
    else
    {
        return [app keyWindow];
    }
}

+ (void)showHint:(NSString *)hint
{
    [Utility showHint:hint yOffset:0];
}

+ (void)showHint:(NSString *)hint yOffset:(float)yOffset
{
    [Utility showHint:hint yOffset:yOffset HUDMode:MBProgressHUDModeCustomView];
}

+ (void)showHint:(NSString *)hint yOffset:(float)yOffset HUDMode:(MBProgressHUDMode)HUDMode
{
    UIView *view = [[UIApplication sharedApplication].delegate window];
    MBProgressHUD *_hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    _hud.userInteractionEnabled = NO;
    _hud.mode = HUDMode;
    _hud.label.text = hint;
    _hud.label.numberOfLines=0;
    _hud.label.font = [UIFont systemFontOfSize:13];
    _hud.margin = 10.f;
    _hud.offset = CGPointMake(0, yOffset);
    _hud.removeFromSuperViewOnHide = YES;
    [_hud hideAnimated:YES afterDelay:3];
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    NSString *MOBILE = @"[0-9]{11}";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:mobileNum];
}

+ (BOOL)isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;
    }
    return NO;
}


+ (void)startTime:(UIButton *)sender
{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"重发验证码？" forState:UIControlStateNormal];
                [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [sender setUserInteractionEnabled:YES];
            });
        }else{
            int seconds = timeout%60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [sender setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [sender setUserInteractionEnabled:NO];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


+ (NSString *)currentTime:(NSDate *)date
{
    NSString *curTime = [NSString stringWithFormat:@"%d", (int)[date timeIntervalSince1970]];
    return curTime;
}

/**
 *  检测文字的Size
 *
 *  @param text             文字
 *  @param font             字体
 *  @param width            最大宽度
 *  @param attributedString 富文本（如果attributedString不为nil 会根据attributedString来检测）
 *
 *  @return 文字的Size
 */
+ (CGSize)getTextString:(NSString *)text textFont:(UIFont *)font frameWidth:(float)width attributedString:(NSMutableAttributedString *)attributedString
{
    CGSize constraint = CGSizeMake(width, MAXFLOAT);
    
    if (!attributedString) {
        
        attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
                                                                                               NSFontAttributeName:font
                                                                                               }];
        
    }
    CGRect rect = [attributedString boundingRectWithSize:constraint
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                                 context:nil];
    CGSize size = rect.size;
    return size;
}
@end
